<?php

class sgeModelGenerator extends sfDoctrineGenerator
{

	public function getReadableName()
	{
		return isset($this->params['readable_name']) ? $this->params['readable_name'] : sfInflector::humanize($this->getModuleName());
	}

	public function getDefaultFieldsConfiguration()
	{
		$fields = array();

		$names = array();
		foreach ($this->getColumns() as $name => $column)
		{
			$names[] = $name;
			$fields[$name] = array_merge(array(
				'is_link'      => (Boolean) $column->isPrimaryKey(),
				'is_real'      => true,
				'is_partial'   => false,
				'is_component' => false,
				'type' => $this->getType($column),
			), isset($this->config['fields'][$name]) ? $this->config['fields'][$name] : array());

			//FIXME: usado en filtros del reporte, es lo único que se ha agregado
			if ($column->isForeignKey())
			{
				$fields[$name]['foreign_class'] = $column->getForeignClassName();
			}
		}

		foreach ($this->getManyToManyTables() as $tables)
		{
			$name = sfInflector::underscore($tables['alias']).'_list';
			$names[] = $name;
			$fields[$name] = array_merge(array(
				'is_link'      => false,
				'is_real'      => false,
				'is_partial'   => false,
				'is_component' => false,
				'type'         => 'Text',
			), isset($this->config['fields'][$name]) ? $this->config['fields'][$name] : array());
		}

		if (isset($this->config['fields']))
		{
			foreach ($this->config['fields'] as $name => $params)
			{
				if (in_array($name, $names))
				{
					continue;
				}

				$fields[$name] = array_merge(array(
					'is_link'      => false,
					'is_real'      => false,
					'is_partial'   => false,
					'is_component' => false,
					'type'         => 'Text',
				), is_array($params) ? $params : array());
			}
		}

		unset($this->config['fields']);

		return $fields;
	}

	public function isAuditableModel()
	{
		return Doctrine_Core::getTable($this->modelClass)->hasTemplate('Auditable');
	}

	public function getCompareFieldsConfiguration()
	{
		$versionName = AuditableLog::getVersionClassName($this->modelClass);

		//se eliminan las columnas que guardan la información de auditoría
		$fields = array_diff(Doctrine_Core::getTable($versionName)->getColumnNames(), AuditableLog::getAuditColumnNames());
		$columns = $this->getColumns();

		foreach ($fields as $name => $value)
		{
			//cambia los nombres de las foreign keys, las consultas en lib/model/tables
			//devuelven un array con los nombres del modelo en lugar de la foreign key
			//if (substr($value, -3) === '_id')
			if ($columns[$value]->isForeignKey())
			{
				//$fields[$name] = ucfirst(substr($value, 0, -3));
				$fields[$name] = $columns[$value]->getForeignClassName();
			}
		}

		return $fields;
	}

}